package com.luyue.zagj.activity.myAccount;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.jude.easyrecyclerview.decoration.SpaceDecoration;
import com.luyue.zagj.BaseActivity;
import com.luyue.zagj.R;
import com.luyue.zagj.adapter.VhicleManaAdapter;
import com.luyue.zagj.adapter.VhicleManaViewHolder;
import com.luyue.zagj.domin.News;
import com.luyue.zagj.domin.NewsGson;
import com.luyue.zagj.httpData.DemoApi;
import com.luyue.zagj.utils.PixUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class VehicleManageActivity extends BaseActivity {

    @Bind(R.id.vehicle_mng_cancel_btn)
    Button vehicleMngCancelBtn;
    @Bind(R.id.vehicle_mng_add_btn)
    Button vehicleMngAddBtn;
    @Bind(R.id.vehicle_mng_top_rl)
    RelativeLayout vehicleMngTopRl;
    @Bind(R.id.vehicle_mng_lv)
    EasyRecyclerView vehicleRv;


    private int page = 0;
    //真数据时候换掉
    private VhicleManaAdapter adapter;
    private List<News> newsList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vehicle_manage);
        ButterKnife.bind(this);
        setLv();
        initData();
    }

    private void setLv() {
        vehicleRv.setAdapter(adapter = new VhicleManaAdapter(this));
        vehicleRv.setLayoutManager(new LinearLayoutManager(this));
        //添加边框
        SpaceDecoration itemDecoration = new SpaceDecoration((int) PixUtil.convertDpToPixel(5, this));
        itemDecoration.setPaddingEdgeSide(true);
        itemDecoration.setPaddingStart(true);
        itemDecoration.setPaddingHeaderFooter(false);
        vehicleRv.addItemDecoration(itemDecoration);

        //更多加载
        adapter.setMore(R.layout.view_more, new RecyclerArrayAdapter.OnMoreListener() {
            @Override
            public void onMoreShow() {
                initData();
            }

            @Override
            public void onMoreClick() {

            }
        });
        //写刷新事件
        vehicleRv.setRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                vehicleRv.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        adapter.clear();
                        page = 0;
                        initData();
                    }
                }, 1000);
            }
        });
        RecyclerView recyclerView = vehicleRv.getRecyclerView();
        setOnTouch(recyclerView);
        //点击事件
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {


                ArrayList<String> data = new ArrayList<String>();
                //adapter.holder.setInvisibleItem((int) adapter.holder.getItemId());


//                data.add(adapter.getAllData().get(position).getPicUrl());

//                Intent intent = new Intent(getActivity(), NewsDetailsActivity.class);
//                //用Bundle携带数据
//                Bundle bundle = new Bundle();
//                bundle.putStringArrayList("data", data);
//                intent.putExtras(bundle);
//                startActivity(intent);
                //此步获得选中状态
                //adapter.getAllData().get(position).g1
//                adapter.clear();
//                page = 0;
//                //接口调用  上传数据
//
//                initData();
            }
        });
    }

    /**
     * 设置reCycleView的触摸事件
     * @param rv
     */
    public  void setOnTouch(RecyclerView rv){
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {

            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                //actionState : action状态类型，有三类 ACTION_STATE_DRAG （拖曳），ACTION_STATE_SWIPE（滑动），ACTION_STATE_IDLE（静止）
                int dragFlags = makeFlag(ItemTouchHelper.ACTION_STATE_DRAG, ItemTouchHelper.UP | ItemTouchHelper.DOWN
                        | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);//支持上下左右的拖曳
                int swipeFlags = makeMovementFlags(ItemTouchHelper.ACTION_STATE_SWIPE, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);//表示支持左右的滑动
                return makeMovementFlags(dragFlags, swipeFlags);//直接返回0表示不支持拖曳和滑动
            }

            /**
             * @param recyclerView attach的RecyclerView
             * @param viewHolder 拖动的Item
             * @param target 放置Item的目标位置
             * @return
             */
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                int fromPosition = viewHolder.getAdapterPosition();//要拖曳的位置
                int toPosition = target.getAdapterPosition();//要放置的目标位置
                Collections.swap(newsList, fromPosition, toPosition);//做数据的交换
                adapter.notifyItemMoved(fromPosition, toPosition);
                if (toPosition==0||fromPosition==0||(toPosition==1&&fromPosition==0)){
                    VhicleManaViewHolder targetHolder= (VhicleManaViewHolder) target;
                    targetHolder.check.setVisibility(View.INVISIBLE);


                    VhicleManaViewHolder holder= (VhicleManaViewHolder) viewHolder;
                    holder.check.setVisibility(View.VISIBLE);

                }
                return true;
            }

            /**
             * @param viewHolder 滑动移除的Item
             * @param direction
             */
            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();//获取要滑动删除的Item位置
                if (position==0){
                    adapter.notifyDataSetChanged();
                }
                adapter.remove(position);//删除数据
                adapter.notifyItemRemoved(position);
            }

        });
        itemTouchHelper.attachToRecyclerView(rv);
    }

    private void initData() {
        Log.d("page", page + "");
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.tianapi.com/")
                //String
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())//添加 json 转换器
                //    compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//添加 RxJava 适配器
                .build();

        DemoApi apiManager = retrofit.create(DemoApi.class);//这里采用的是Java的动态代理模式

        apiManager.getNewsData("528f49d2debfd453585f9da6a679c0a1", "10", page)
                .subscribeOn(Schedulers.io())
                .map(new Func1<NewsGson, List<News>>() {
                    @Override
                    public List<News> call(NewsGson newsgson) { //
                        newsList = new ArrayList<News>();
                        for (NewsGson.NewslistBean newslistBean : newsgson.getNewslist()) {
                            News new1 = new News();
                            new1.setTitle(newslistBean.getTitle());
                            new1.setCtime(newslistBean.getCtime());
                            new1.setDescription(newslistBean.getDescription());
                            new1.setPicUrl(newslistBean.getPicUrl());
                            new1.setUrl(newslistBean.getUrl());
                            newsList.add(new1);
                        }
                        return newsList; // 返回类型
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<News>>() {
                    @Override
                    public void onNext(List<News> newsList) {
                        adapter.addAll(newsList);
                    }

                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(VehicleManageActivity.this,
                                "网络连接失败", Toast.LENGTH_LONG).show();
                    }
                });
        page = page + 1;
    }

    @OnClick({R.id.vehicle_mng_cancel_btn, R.id.vehicle_mng_add_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.vehicle_mng_cancel_btn:
                this.finish();
                break;
            case R.id.vehicle_mng_add_btn:
                int count = adapter.getCount();
                VhicleManaViewHolder holder = adapter.holder;
                for (int i = 0; i < count; i++){
                        holder.check.setVisibility(View.INVISIBLE);

                }
                break;
        }
    }
}
